package com.gwtt.simulator.netconf.server;

import com.gwtt.simulator.netconf.subsystem.NetconfSubsystemFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.sshd.server.ServerFactoryManager;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;

import java.nio.file.Paths;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Slf4j
public class NetconfServer {

    private SshServer sshServer;

    public static NetconfServer createServer(String host, int port) {
        NetconfServer server = new NetconfServer();
        server.initNetconfServer(host, port);
        return server;
    }

    private void initNetconfServer(String host, int port) {
        log.info("start init netconf server");

        sshServer = SshServer.setUpDefaultServer();
        sshServer.setHost(host);
        sshServer.setPort(port);

        sshServer.getProperties().put(ServerFactoryManager.COMMAND_EXIT_TIMEOUT, TimeUnit.SECONDS.toMillis(10L));
        // 认证
        sshServer.setPasswordAuthenticator(new StaticPasswordAuthenticator());
        // 秘钥生成
        SimpleGeneratorHostKeyProvider keyProvider = new SimpleGeneratorHostKeyProvider(Paths.get("certificate/ssh_server.ser"));
        keyProvider.setAlgorithm("EC");
        sshServer.setKeyPairProvider(keyProvider);
        // 设置netconf子系统
        sshServer.setSubsystemFactories(Collections.singletonList(new NetconfSubsystemFactory()));
        log.info("init netconf server over");
    }

    public void start() throws Exception {
        sshServer.start();
        Thread.sleep(Integer.MAX_VALUE);
    }

}
